<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="searchItemCount"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="codesetCode" label="代码分类编码">
          <FIInput v-model="state.query.codesetCode" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="codesetName" label="代码分类名称">
          <FIInput v-model="state.query.codesetName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="projectName" label="后端项目列表">
          <!-- <FISelect
            v-model="state.query.isAuth"
            valueCustom="value"
            :codeOption="{ codesetCode: 'backendPrjCode' }"
            v-model:key-word="keyWord"
            clearable
          /> -->
          <FISelect
            v-if="arr2.length > 0"
            v-model="state.query.projectName"
            valueCustom="value"
            :options="arr2"
            clearable
          />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="代码分类列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="codesetId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      deletable
      delete-id="deleteCodeset"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleAction"
      @row-delete="deleteRow"
    >
      <!-- <el-table-column label="项目英文名" align="center" width="200"> -->
      <template #projectName="{ scope }">
        <FISelect
          @change="onCellChange"
          v-if="scope.row.isSelected"
          v-model="scope.row.projectName"
          valueCustom="value"
          :options="arr2"
          clearable
        />
        <span v-else>{{ scope.row.projectName }}</span>
      </template>
      <!-- </el-table-column> -->
      <template #headerBtn>
        <!-- <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ id: 'deleteCodeset', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn> -->
        <!-- <FIPopconfirmBtn
          title="您是否确认要刷新缓存？"
          buttonText="刷新缓存"
          api-url="/pageMaint/refreshCache"
          :btn-binds="{ customType: 'border' }"
        >
        </FIPopconfirmBtn> -->
      </template>
    </FITable>
    <!-- <FIModel v-model="isVisible" title="明细设置">
      <InfoForm :node-info="selectedNode"></InfoForm>
  </FIModel> -->
    <assign-post
      ref="childComponent"
      :postShow="postShow"
      @update:postShow="(newValue) => (postShow = newValue)"
      :editData="selectedNode"
      @refresh="refreshTable"
    ></assign-post>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, provide } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import assignPost from './assignPost.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIModel from '@/components/FIModel.vue'

import InfoForm from './infoForm.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiGetbackproject } from '@/api/configEnvMaint/index.ts'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
const route = useRoute()
const isVisible = ref(false)
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
const childComponent = ref(null)
const postShow = ref(false)
// 页面编码
const tableId = 'codesetMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const selectedNode = ref({})
const state = reactive({
  query: {
    codesetCode: '',
    codesetName: '',
    projectName: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const columns: Column[] = reactive([
  // {
  //   label: '代码分类ID',
  //   prop: 'codesetId',
  //   align: 'center',
  //   width: '180',
  //   // editable: false,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '代码分类编码',
    prop: 'codesetCode',
    align: 'center',
    queryName: '',
    required: true,
    editable: true,
    // sortable: true,
    // filterable: true,
    readonly: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { codesetCode: [{ required: true }] },
    },
  },
  {
    label: '代码分类名称',
    prop: 'codesetName',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    editType: 'input',
    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { codesetName: [{ required: true, message: '请输入页面名称', trigger: 'blur' }] },
    },
  },
  {
    label: '备注',
    prop: 'remark',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    // filterable: true,
    modelValue: { inputValue: '' },
    // sortable: true,
    sortValue: '',
    editConfig: {
      rules: { remark: [{ required: false, message: '请输入备注', trigger: 'blur' }] },
    },
  },
  {
    label: '所属项目',
    prop: 'projectName',
    align: 'center',
    editable: true,
    // filterable: true,
    // sortable: true,
    // modelValue: { inputValue: '' },
    // editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    // editConfig: {
    //   rules: { projectName: [{ required: true, message: '请输入所属项目', trigger: 'blur' }] },
    // },
  },

  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [
      // { id: 'delete', type: 'delete' },
      // { id: 'b5555', type: 'add' },
      { id: 'openItem', type: 'action_openItem' },
      { id: 'b5555', type: 'add' },
    ],
  },
])
// 在这里处理验证

function validateProjectName(newValue) {
  const isValid = arr2.value.some((option) => option.value === newValue)

  if (!isValid) {
    alert('Invalid project name selected!')
    // 验证失败，你可以抛出错误，显示警告，或者在表格行上显示错误状态
    // scope.row.$errors = ['Invalid project name selected!'];
  } else {
    // 清除错误状态
    // scope.row.$errors = null;
  }
}

const onCellChange = (e) => {
  const isValid = e !== '' && arr2.value.some((option) => option.value === e)
  console.log(isValid, 111)
  if (!isValid) {
    // 验证失败，你可以抛出错误，显示警告，或者在表格行上显示错误状态
    // console.error('请选择所属项目');
    // useMessage().warning('请选择项目')
    return false
  }
  return true
}
const handleAction = (item, rowData, butoninfo) => {
  console.log(childComponent.value)
  postShow.value = true
  selectedNode.value = rowData
  // childComponent.value.clearTaleble()
}
const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const refreshTable = () => {
  pageConfig.currentPage = 1
  searchFn()
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    // apiRequestPost('/codesetMaint/queryCodeset', state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = (row) => {
  // console.log(row.projectName,99999)
  // if (checkedRows.value.every((row) => onCellChange(row.projectName))) {
  // 所有行的projectName都有效，进行保存操作
  isTableLoading.value = true
  isTableLoading.value = true
  saveSuccessful.value = false
  const apiUrl = proxy.$Button_api('saveCodeset', route.name)
  apiRequestPost(apiUrl, checkedRows.value)
    // apiRequestPost('/codesetMaint/saveCodeset', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        useMessage().success(res.data.message)
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
  // ...你的保存逻辑...
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.codesetId) ids.push(item?.codesetId)
    })
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('deleteCodeset', route.name)
  apiRequestPost(apiUrl, ids)
    // apiRequestPost('/codesetMaint/deleteCodeset', ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  console.log(data)
  if (!onCellChange(data.projectName)) {
    handleSave(data, 'add')
  }
}
watch(
  () => columns.values,
  (newValue) => {},
  { deep: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
const arr2 = ref([])
const getProjectname = () => {
  apiGetbackproject().then((res) => {
    // console.log(res.data.data,99999999999999999999)
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `[${item.projectEname}] ${item.projectCname}`
          item.value = item.projectEname
        })
      if (Array.isArray(res.data.data)) {
        // const newArray = res.data.data.map((item) => ({
        //   label: `【${item.cacheCname}】${item.cacheEname}`,
        //   value: item.remark,
        // }));

        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr2.value = res.data.data
        console.log(arr2.value)
      }
    }
  })
}
provide('dataList', state)
onMounted(() => {
  getProjectname()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
